package com.easy.interceptor;

import com.alibaba.fastjson.JSON;
import com.easy.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 用户需要登录   系统会给浏览器发送一个token
        //2.浏览器接收到这个token  需要记录下来
        //3.之后浏览器每次发送请求都需携带这个token      将token放到Header中    如果有token就是登录过的   如果没有token就是没有登陆过
        //4.在拦截器中拦截每个请求,获取Header中的token  如果获取到就放行,没获取到就截止

        String token=request.getHeader("authentication");
        if(token==null||token.isEmpty()){
            Result result=Result.fail(401,"认证失败");
            //需要转成json格式
            String json=JSON.toJSONString(result);
            response.getWriter().write(json);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
